<template>
  <div class="app-container">
    <el-alert type="success" :closable="false" class="margin-bottom">
      <template slot="title">
        如果需要使用 ssh 认证, 请 <el-button type="text" @click="downloadPublicKey">下载 publicKey</el-button> 并传到对应应用
      </template>
    </el-alert>
    <el-row>
      <el-col :span="5">
        <el-table
          :data="modules"
          border
          stripe
          style="width: 100%"
          highlight-current-row
          size="mini"
        >
          <el-table-column
            prop="name"
            label="模块"
          />
          <el-table-column
            fixed="right"
            label="操作"
            width="100"
          >
            <template slot-scope="scope">
              <el-button type="text" class="" size="small" @click="loadModuleConnects(scope.row.name)">查看连接</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <el-col :span="18" class="margin-left">
        <el-button :disabled="!choseModule" class="margin-bottom" size="small" type="primary" @click="preCreateConnect">新建 {{ choseModule }} 连接</el-button>
        <el-table
          :data="moduleConnects"
          border
          stripe
          style="width: 100%"
          size="mini"
        >
          <el-table-column type="index" width="55" />
          <el-table-column
            prop="connectInput.baseName"
            label="基础名"
            width="150"
            sortable
          />
          <el-table-column
            prop="path"
            label="路径"
            width="210"
          />
          <el-table-column
            prop="connectInput.configTypeName"
            label="配置格式"
            width="70"
          />
          <el-table-column
            prop="lastUpdateTime"
            label="最后更新时间"
            width="180"
          />
          <el-table-column
            prop="lastAccessTime"
            label="最后访问时间"
            width="180"
          />
          <el-table-column
            prop="lastUpdateUser"
            label="更新人"
          />
          <el-table-column
            prop="connectInput.group"
            label="组织"
          />

          <el-table-column
            fixed="right"
            label="操作"
            width="150"
          >
            <template slot-scope="scope">
              <el-button type="text" class="" size="small" @click="readConnect(scope.row.connectInput)">详情</el-button>
              <el-button type="text" class="" size="small" @click="delConnects(scope.row.connectInput.baseName)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <!-- 新建连接 -->
    <el-dialog :visible.sync="dialog.add.visible" :title="dialog.add.title">
      <el-form ref="addConnectForm" size="mini" label-position="right" label-width="120px" :model="dialog.add.connectInput" :rules="dialog.add.rules">
        <el-form-item label="模块名" prop="module">
          <el-input v-model="dialog.add.connectInput.module" placeholder="模块名" readonly size="small" />
        </el-form-item>
        <el-form-item label="基础名" prop="baseName">
          <el-input v-model="dialog.add.connectInput.baseName" placeholder="基础名" size="small" />
        </el-form-item>
        <el-form-item label="配置文件格式" prop="configTypeName">
          <el-input v-model="dialog.add.connectInput.configTypeName" placeholder="配置文件格式" readonly size="small" />
        </el-form-item>
        <el-row>
          <el-col :span="7">
            <div v-if="dialog.add.accessGroups" style="height: 300px;overflow-y: scroll">
              <el-tree ref="groupTree" :data="dialog.add.accessGroups" :check-strictly="true" node-key="path" :default-expanded-keys="['/']" :props="{label: 'path'}" show-checkbox />
            </div>
          </el-col>
          <el-col :span="16">
<!--            <monaco-editor :key="dialog.add.randomkey" height="300" :language="dialog.add.connectInput.configTypeName" :code="dialog.add.connectInput.content" @mounted="editorMounted" @codeChange="onCodeChange" />-->
            <monaco-editor ref="addEditor" :language="dialog.add.connectInput.configTypeName" :code="dialog.add.connectInput.content" />
          </el-col>
        </el-row>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button class="margin-bottom" type="primary" size="small" @click="writeConfig">确定</el-button>
      </span>
    </el-dialog>

    <!-- 更新连接内容 -->
    <el-dialog :visible.sync="dialog.editcontent.visible" width="80%" :title="dialog.editcontent.title">
<!--      <monaco-editor key="edit" height="400" :language="dialog.editcontent.connectInput.configTypeName" :code="dialog.editcontent.content" @mounted="modifyEditorMounted" @codeChange="modifyEditorCodeChange" />-->
      <monaco-editor ref="modifyEditor" :language="dialog.editcontent.connectInput.configTypeName" :code="dialog.editcontent.content"/>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" class="margin-bottom margin-left" @click="updateContent">保存</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import core from '@/api/core'
import security from '@/api/security'

import { mapGetters } from 'vuex'

import MonacoEditor from '@/views/components/MonacoEditor'

export default {
  name: 'connect',
  components: {MonacoEditor},
  data() {
    return {
      modules: [],
      choseModule: null,
      moduleConnects: [],
      dialog: {
        add: {
          title: '新建连接',
          visible: false,
          randomkey: 1,
          connectInput: {
            module: null,
            baseName: null,
            configTypeName: null,
            group: null,
            content: null
          },
          accessGroups: [],
          rules: {
            module: [{ required: true, message: '模块名必填', trigger: 'blur' }],
            baseName: [{ required: true, message: '基础名必填', trigger: 'blur' }],
            configTypeName: [{ required: true, message: '配置类型必填', trigger: 'blur' }]
          }
        },
        editcontent: {
          title: '编辑连接内容',
          visible: false,
          content: null,
          connectInput: {}
        }
      }
    }
  },
  mounted() {
    this.loadModules()
  },
  methods: {
    downloadPublicKey() {
      core.downloadPublicKey()
    },
    delConnects(baseName) {
      core.security.delConnect(this.choseModule, baseName).then(res => {
        this.loadModuleConnects(this.choseModule)
      })
    },
    loadModules() {
      core.security.modules().then(res => {
        this.modules = res.data.map(moduleName => ({ name: moduleName }))
        if (this.modules && this.modules.length > 0) {
          if (!this.choseModule) {
            this.loadModuleConnects(this.modules[0].name)
          }
        }
      })
    },
    loadModuleConnects(module) {
      this.choseModule = module
      core.security.moduleConnects(module).then(res => {
        this.moduleConnects = res.data
      })
    },
    readConnect(connInput) {
      this.dialog.editcontent.title = '编辑 ' + this.choseModule + ' [ ' + connInput.baseName + ' ] ' + ' 连接内容'
      core.security.loadContent(this.choseModule, connInput.baseName).then(res => {

        this.dialog.editcontent.connectInput = connInput
        this.dialog.editcontent.content = res.data
        this.dialog.editcontent.visible = true
      })
    },
    preCreateConnect() {
      this.dialog.add.connectInput.module = this.choseModule
      this.dialog.add.visible = true
      this.dialog.add.title = '新建 ' + this.choseModule + ' 连接'

      // 如果需要权限, 需要加载用户可访问组织
      if (this.needSecurity) {
        // 如果需要权限
        security.accessGroups().then(res => {
          this.dialog.add.accessGroups = [res.data]
        })
      } else {
        this.dialog.add.accessGroups = [{ path: '/', children: [] }]
      }

      // 加载连接模板
      core.security.connectTemplate(this.choseModule).then(res => {
        this.dialog.add.connectInput.configTypeName = res.data.configTypeName
        this.dialog.add.connectInput.content = res.data.content
        this.dialog.add.randomkey = Math.floor(Math.random() * (10, 1000000012313))
      })
    },
    writeConfig() {
      this.$refs['addConnectForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        // 获取 group
        const groups = this.$refs.groupTree.getCheckedKeys()
        // 获取编辑器文本内容
        this.dialog.add.connectInput.content = this.$refs.addEditor.getValue();
        if (groups.length === 0) {
          this.$message('需要选择一个组织节点做为连接的组织以方便权限过滤')
          return
        }
        if (groups.length > 1) {
          this.$confirm('只能选择一个节点做为连接分组,现将使用 ' + groups[0] + ' 做为分组, 确定?', '警告', { type: 'warning' }).then(() => {
            this.dialog.add.connectInput.group = groups[0]

            core.security.writeConfig(this.dialog.add.connectInput).then(res => {
              this.loadModuleConnects(this.choseModule)
              this.dialog.add.visible = false
            })
          }).catch(() => {})
        } else {
          this.dialog.add.connectInput.group = groups[0]
          core.security.writeConfig(this.dialog.add.connectInput).then(res => {
            this.loadModuleConnects(this.choseModule)
            this.dialog.add.visible = false
          })
        }
      })
    },
    updateContent() {
      // console.log(this.dialog.editcontent.content,'content')
      this.dialog.editcontent.content = this.$refs.modifyEditor.getValue();
      const afterConnect = Object.assign(this.dialog.editcontent.connectInput, { content: this.dialog.editcontent.content })
      core.security.writeConfig(afterConnect).then(res => {
        this.loadModuleConnects(this.choseModule)
        this.dialog.editcontent.visible = false
      })
    }
  },
  computed: {
    ...mapGetters(['needSecurity'])
  }

}
</script>


